<script setup lang="ts">
import { computed } from 'vue';

import { getDictObj } from '@vben/hooks';
import { isValidColor, TinyColor } from '@vben/utils';

import { Badge } from 'ant-design-vue';

interface DictTagProps {
  /**
   * 字典类型
   */
  type?: string;
  /**
   * 字典值
   */
  value: any;
  /**
   * 字典选项
   */
  options?: any;
  /**
   * 图标
   */
  icon?: string;
}

const props = defineProps<DictTagProps>();

/** 获取字典标签 */
const dictTag = computed(() => {
  // 校验参数有效性
  if (props.value === undefined || props.value === null) {
    return null;
  }
  let dict = null;
  if (props.type) {
    // 获取字典对象
    dict = getDictObj(props.type, String(props.value));
    if (!dict) {
      return null;
    }
  } else {
    let myOptions = props.options;
    if (myOptions === null || myOptions === undefined) {
      myOptions = [
        { label: '是', value: true, colorType: 'primary' },
        { label: '否', value: false, colorType: 'danger' },
      ];
    }

    dict =
      myOptions.find(
        (d) => d.value === props.value || d.value === props.value.toString(),
      ) ?? null;
  }
  if (!dict) {
    return null;
  }
  // 处理颜色类型
  let colorType = dict.colorType;
  switch (colorType) {
    case 'danger': {
      colorType = 'error';
      break;
    }
    case 'info': {
      colorType = 'default';
      break;
    }
    case 'primary': {
      colorType = 'processing';
      break;
    }
    default: {
      if (!colorType) {
        colorType = 'default';
      }
    }
  }

  if (isValidColor(dict.cssClass)) {
    colorType = new TinyColor(dict.cssClass).toHexString();
  }

  return {
    label: dict.label || '',
    colorType,
    cssClass: dict.cssClass,
  };
});
</script>

<template>
  <Badge
    v-if="dictTag"
    :status="dictTag.cssClass ? '' : dictTag.colorType"
    :color="dictTag.cssClass ? dictTag.cssClass : dictTag.colorType"
    :text="dictTag.label"
  />
</template>
